import { ref, computed, type Ref, onUnmounted } from 'vue';

interface TypewriterOptions {
  /** 字符输入间隔时间（毫秒） */
  charInterval?: number;
  /** 行间额外停顿时间（毫秒） */
  linePause?: number;
  /** 是否自动开始 */
  autoStart?: boolean;
  /** 当开始打字（start 被调用） */
  onStart?: () => void;
  /** 当暂停 */
  onPause?: () => void;
  /** 当恢复 */
  onResume?: () => void;
  /** 每打印一个字符 */
  onChar?: (char: string, lineIndex: number, colIndex: number) => void;
  /** 当一行打印完成（准备跳下一行） */
  onLineEnd?: (lineIndex: number, lineText: string) => void;
  /** 当全部打印完成 */
  onFinish?: () => void;
  /** 当重置 */
  onReset?: () => void;
}

interface TypewriterReturn {
  /** 当前显示的文字 */
  displayedText: Readonly<Ref<string>>;
  /** 是否正在运行 */
  isRunning: Readonly<Ref<boolean>>;
  /** 是否暂停 */
  isPaused: Readonly<Ref<boolean>>;
  /** 是否已完成 */
  isFinished: Readonly<Ref<boolean>>;
  /** 开始打字 */
  start: () => void;
  /** 暂停打字 */
  pause: () => void;
  /** 恢复打字 */
  resume: () => void;
  /** 跳过当前行 */
  skipLine: () => void;
  /** 跳过全部 */
  skip: () => void;
  /** 重置状态 */
  reset: () => void;
}

export function useTypewriter(
  lines: Ref<string[]>,
  options: TypewriterOptions = {}
): TypewriterReturn {
  const {
    charInterval = 80,
    linePause = 400,
    autoStart = false,
    onStart,
    onPause,
    onResume,
    onChar,
    onLineEnd,
    onFinish,
    onReset,
  } = options;

  // 状态管理
  const currentLine = ref(0);
  const currentCol = ref(0);
  const isRunning = ref(false);
  const isPaused = ref(false);
  const timer = ref<number | null>(null);

  // 计算属性
  const displayedText = computed(() => {
    return lines.value
      .slice(0, currentLine.value + 1)
      .map((line, index) =>
        index === currentLine.value ? line.slice(0, currentCol.value) : line
      )
      .join('\n');
  });

  const isFinished = computed(
    () => currentLine.value >= lines.value.length && currentCol.value === 0
  );

  // 工具函数
  const clearTimer = (): void => {
    if (timer.value !== null) {
      clearTimeout(timer.value);
      timer.value = null;
    }
  };

  const scheduleNextTick = (delay: number): void => {
    timer.value = window.setTimeout(tick, delay);
  };

  const moveToNextLine = (): void => {
    currentLine.value++;
    currentCol.value = 0;
  };

  const completeCurrentLine = (): void => {
    if (currentLine.value < lines.value.length) {
      currentCol.value = lines.value[currentLine.value]?.length ?? 0;
    }
  };

  // 核心逻辑
  const tick = (): void => {
    if (isPaused.value) return;

    const hasMoreLines = currentLine.value < lines.value.length;
    if (!hasMoreLines) {
      isRunning.value = false;
      onFinish?.();
      return;
    }

    const currentLineText = lines.value[currentLine.value];
    if (!currentLineText) return;
    const hasMoreChars = currentCol.value < currentLineText.length;

    if (hasMoreChars) {
      const ch = currentLineText[currentCol.value];
      currentCol.value++;
      onChar?.(ch ?? '', currentLine.value, currentCol.value - 1);
      scheduleNextTick(charInterval);
    } else {
      moveToNextLine();
      const shouldContinue = currentLine.value < lines.value.length;
      if (shouldContinue) {
        scheduleNextTick(linePause);
      } else {
        isRunning.value = false;
        onFinish?.();
      }
    }
  };

  // 控制方法
  const start = (): void => {
    if (isRunning.value) return;

    // 如果已经完成，先重置
    if (isFinished.value) {
      reset();
    }

    isRunning.value = true;
    isPaused.value = false;
    onStart?.();
    tick();
  };

  const pause = (): void => {
    if (!isRunning.value || isPaused.value) return;

    isPaused.value = true;
    clearTimer();
    onPause?.();
  };

  const resume = (): void => {
    if (!isRunning.value || !isPaused.value) return;

    isPaused.value = false;
    onResume?.();
    tick();
  };

  const skipLine = (): void => {
    if (!isRunning.value) return;
    if (currentLine.value >= lines.value.length) return;

    clearTimer();
    completeCurrentLine();
    const curLineText = lines.value[currentLine.value];
    onLineEnd?.(currentLine.value, curLineText ?? '');
    moveToNextLine();

    const shouldContinue = currentLine.value < lines.value.length;
    if (shouldContinue) {
      scheduleNextTick(linePause);
    } else {
      isRunning.value = false;
      onFinish?.();
    }
  };

  const skip = (): void => {
    clearTimer();
    currentLine.value = lines.value.length;
    currentCol.value = 0;
    isRunning.value = false;
    isPaused.value = false;
    onFinish?.();
  };

  const reset = (): void => {
    clearTimer();
    currentLine.value = 0;
    currentCol.value = 0;
    isRunning.value = false;
    isPaused.value = false;
    onReset?.();
  };

  // 生命周期管理
  onUnmounted(() => {
    clearTimer();
  });

  // 自动开始
  if (autoStart) {
    start();
  }

  return {
    displayedText: displayedText,
    isRunning: isRunning,
    isPaused: isPaused,
    isFinished: isFinished,
    start,
    pause,
    resume,
    skipLine,
    skip,
    reset,
  };
}
